package co.com.app.social.controllers;

import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.brickred.socialauth.AuthProvider;
import org.brickred.socialauth.Contact;
import org.brickred.socialauth.Profile;
import org.brickred.socialauth.SocialAuthConfig;
import org.brickred.socialauth.SocialAuthManager;
import org.brickred.socialauth.util.SocialAuthUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Cristian Velasquez
 *
 */
@Controller
public class SocialController {

	@Autowired
	private Properties socialAuthProperties;
	private @Value("#{confAuthProperties['social.example.domain']}") String urlDomain;
	private @Value("#{confAuthProperties['social.example.messageToPublish']}") String messagePublish;

	
	/**
	 * @param request
	 * @param id, identificador del servicio: facebook, twitter, google, yahoo, hotmail
	 * @param action, accion a ejecutar: publicar (publish) o traer contactos (success)
	 * @return redireccion a la url de autenticacion del servicio
	 * @throws Exception
	 */
	@RequestMapping("/socialauth.do")
	public String authSocial(final HttpServletRequest request, @RequestParam("id") String id, @RequestParam("action") String action)throws Exception {
		SocialAuthConfig config = SocialAuthConfig.getDefault();
		config.load(socialAuthProperties);
		SocialAuthManager manager = new SocialAuthManager();
		manager.setSocialAuthConfig(config);
		String successUrl = urlDomain;
		if (action != null && action.equals("publish")) {
			successUrl += "/publish.do";
		}else{
			successUrl += "/success.do";
		}
		String url = manager.getAuthenticationUrl(id, successUrl);
		request.getSession().setAttribute("authManager", manager);

		return "redirect:"+url;
	}

	/**
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/success.do")
	public String success(final HttpServletRequest request, Model model)throws Exception {

		SocialAuthManager manager = (SocialAuthManager)request.getSession().getAttribute("authManager");
		Map<String, String> paramsMap = SocialAuthUtil.getRequestParametersMap(request); 
		AuthProvider provider = manager.connect(paramsMap);
		Profile p = provider.getUserProfile();
		List<Contact> contactsList = provider.getContactList();

		model.addAttribute("profile", p);
		model.addAttribute("contactsList", contactsList);

		return "contacts";
	}

	/**
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/publish.do")
	public String publish(final HttpServletRequest request, Model model)throws Exception {

		try {
			SocialAuthManager manager = (SocialAuthManager)request.getSession().getAttribute("authManager");
			Map<String, String> paramsMap = SocialAuthUtil.getRequestParametersMap(request); 
			AuthProvider provider = manager.connect(paramsMap);

			provider.updateStatus(messagePublish);

			model.addAttribute("messagePublish", "Se ha publicado correctamente el mensaje");

		} catch (Exception e) {
			model.addAttribute("messagePublish", "No se publicado correctamente el mensaje, por favor intente mas tarde.");
		}		
		return "publish";
	}

	/**
	 * @param emails: Emails para enviar por correo separados por ,
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/send.do")
	public @ResponseBody String send(@RequestParam("emails") String emails)throws Exception {

		//TODO: Integrar con la funcionalidad de enviar correos.
		for (String email : emails.split(",")) {
			System.out.println(email);
		}
		
		return "Los correos han sido enviados correctamente.";
	}
}